package pri.zjy.interview;

/**
 * @author zhangjy
 * @description
 * @date 2025/5/16 16:05
 */
public class Test2 {

    /**
     * * Given a sorted (ascending) integer array nums of n elements and a target value targetValue,
     * * write a function to search for targetValue in nums.
     * * If the targetValue exists, return its index; otherwise, return -1.
     * * Example 1:
     * * Input: nums = [-1,0,3,5,9,12], target = 9
     * * Output: 4
     * * Explanation: 9 appears in nums and its index is 4.
     * * Example 2:
     * * Input: nums = [-1,0,3,5,9,12], target = 2
     * * Output: -1
     * * Explanation: 2 does not exist in nums, so return -1.
     */

    public static void main(String[] args) {
        Test2 test2 = new Test2();
        int[] nums = {-1, 0, 3, 5, 9, 12};
        int target = 100;

        System.out.println(test2.search(nums, target));
    }
    public int search(int[] nums, int target) {
        if (nums.length == 0) return -1;

        int left = 0, right = nums.length - 1, mid;
        while (left < right) {
            mid = left + (right - left) / 2;
            // 比target大，则right左移
            if (target < nums[mid]) {
                right--;
            } else if (target > nums[mid]) {
                // 比target小，则left右移
                left++;
            } else {
                return mid;
            }
        }

        return -1;
    }

}
